import React, { useState, useEffect } from 'react';
import { LeftOutline, RightOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { api } from '../../../utils/request';
import { authManager } from '../../../utils/auth';
import './Individual.css';

interface UserProfile {
  id: number;
  name: string;
  phone: string;
  avatar: string;
  weight: string;
  height: string;
  birthday: string;
  img: string;
  created_at: string;
  updated_at: string;
}

const Individual: React.FC = () => {
  const navigate = useNavigate();
  const [userData, setUserData] = useState<UserProfile>({
    id: 1,
    name: 'Koto',
    phone: '13800138000',
    avatar: '/image/nv1.jpg',
    weight: '55kg',
    height: '168cm',
    birthday: '1992-10-15',
    img: '/image/nv1.jpg',
    created_at: '',
    updated_at: ''
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [errors, setErrors] = useState<{[key: string]: string}>({});
  const [successMessage, setSuccessMessage] = useState('');

  useEffect(() => {
    fetchUserProfile();
  }, []);

  // 输入验证函数
  const validateInput = (field: string, value: string) => {
    const newErrors = { ...errors };
    
    switch (field) {
      case 'name':
        if (!value.trim()) {
          newErrors.name = '姓名不能为空';
        } else if (value.trim().length < 2) {
          newErrors.name = '姓名至少需要2个字符';
        } else {
          delete newErrors.name;
        }
        break;
      case 'phone':
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!value.trim()) {
          newErrors.phone = '手机号不能为空';
        } else if (!phoneRegex.test(value.trim())) {
          newErrors.phone = '请输入正确的手机号格式';
        } else {
          delete newErrors.phone;
        }
        break;
      case 'weight':
        const weight = parseFloat(value.replace('kg', ''));
        if (!value.trim()) {
          newErrors.weight = '体重不能为空';
        } else if (isNaN(weight) || weight < 20 || weight > 300) {
          newErrors.weight = '请输入合理的体重(20-300kg)';
        } else {
          delete newErrors.weight;
        }
        break;
      case 'height':
        const height = parseFloat(value.replace('cm', ''));
        if (!value.trim()) {
          newErrors.height = '身高不能为空';
        } else if (isNaN(height) || height < 100 || height > 250) {
          newErrors.height = '请输入合理的身高(100-250cm)';
        } else {
          delete newErrors.height;
        }
        break;
      case 'birthday':
        if (!value) {
          newErrors.birthday = '生日不能为空';
        } else {
          const birthDate = new Date(value);
          const today = new Date();
          if (birthDate > today) {
            newErrors.birthday = '生日不能是未来日期';
          } else if (today.getFullYear() - birthDate.getFullYear() > 150) {
            newErrors.birthday = '请输入合理的生日';
          } else {
            delete newErrors.birthday;
          }
        }
        break;
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 头像上传处理函数
  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      // 检查文件大小 (限制为2MB)
      if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
      }
      
      // 创建预览URL
      const reader = new FileReader();
      reader.onload = (event) => {
        const result = event.target?.result as string;
        setUserData({...userData, avatar: result, img: result});
      };
      reader.readAsDataURL(file);
    }
  };

  const fetchUserProfile = async () => {
    try {
      // 获取登录用户信息
      const userInfo = authManager.getUserInfo();
      if (!userInfo || !userInfo.phone) {
        alert('请先登录');
        navigate('/login');
        return;
      }

      console.log('获取登录用户信息:', userInfo);
      
      // 先尝试使用认证API获取当前登录用户的数据
      const response = await api.get('http://localhost:5000/api/user/profile');
      
      if (response.status === 401) {
        alert('登录已过期，请重新登录');
        navigate('/login');
        return;
      }
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      // 确保日期格式正确
      if (data.birthday && !/^\d{4}-\d{2}-\d{2}$/.test(data.birthday)) {
        const date = new Date(data.birthday);
        data.birthday = date.toISOString().split('T')[0];
      }
      setUserData(data);
    } catch (error) {
      console.error('获取用户资料失败:', error);
      
      // 如果认证API失败，使用登录用户的手机号获取数据
      try {
        const userInfo = authManager.getUserInfo();
        if (userInfo && userInfo.phone) {
          console.log('使用登录用户手机号获取数据:', userInfo.phone);
          const testResponse = await fetch(`http://localhost:5000/api/user/phone/${userInfo.phone}`);
          if (testResponse.ok) {
            const testData = await testResponse.json();
            // 确保日期格式正确
            if (testData.birthday && !/^\d{4}-\d{2}-\d{2}$/.test(testData.birthday)) {
              const date = new Date(testData.birthday);
              testData.birthday = date.toISOString().split('T')[0];
            }
            setUserData(testData);
            return;
          }
        }
      } catch (testError) {
        console.error('使用手机号获取数据失败:', testError);
      }
      
      // 如果所有API都失败，使用默认数据
      alert('获取用户资料失败，请检查登录状态');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (saving) return; // 防止重复提交
    
    try {
      // 验证所有字段
      const isNameValid = validateInput('name', userData.name);
      const isPhoneValid = validateInput('phone', userData.phone);
      const isWeightValid = validateInput('weight', userData.weight);
      const isHeightValid = validateInput('height', userData.height);
      const isBirthdayValid = validateInput('birthday', userData.birthday);
      
      if (!isNameValid || !isPhoneValid || !isWeightValid || !isHeightValid || !isBirthdayValid) {
        alert('请检查输入信息是否正确');
        return;
      }
      
      setSaving(true);
      
      // 获取登录用户信息
      const userInfo = authManager.getUserInfo();
      if (!userInfo || !userInfo.phone) {
        alert('请先登录');
        navigate('/login');
        return;
      }

      console.log('使用登录用户手机号保存数据:', userInfo.phone);
      
      // 先尝试使用认证API保存数据
      try {
        console.log('尝试使用认证API保存数据...');
        // 格式化生日为 yyyy-MM-dd 格式
        const formatBirthday = (dateStr: string) => {
          if (!dateStr) return '1990-01-01';
          // 如果已经是 yyyy-MM-dd 格式，直接返回
          if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
            return dateStr;
          }
          // 否则转换为 yyyy-MM-dd 格式
          const date = new Date(dateStr);
          return date.toISOString().split('T')[0];
        };

        const response = await api.put('http://localhost:5000/api/user/profile', {
          name: userData.name ? userData.name.trim() : '',
          weight: userData.weight ? userData.weight.replace('kg', '').replace('未设置', '').trim() : '',
          height: userData.height ? userData.height.replace('cm', '').replace('未设置', '').trim() : '',
          birthday: formatBirthday(userData.birthday),
          img: userData.img && userData.img !== '/image/nv1.jpg' ? userData.img : null
        });

        if (response.ok) {
          const result = await response.json();
          console.log('认证API保存成功:', result);
          setSuccessMessage('个人资料修改成功！');
          // 保存成功后重新获取数据并重新渲染
          await fetchUserProfile();
          // 3秒后清除成功消息
          setTimeout(() => setSuccessMessage(''), 3000);
          return;
        } else if (response.status === 401) {
          alert('登录已过期，请重新登录');
          navigate('/login');
          return;
        } else {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
      } catch (authError) {
        console.error('认证API保存失败:', authError);
        
        // 如果认证API失败，使用登录用户的手机号保存数据
        try {
          console.log('尝试使用手机号API保存数据...');
          // 格式化生日为 yyyy-MM-dd 格式
          const formatBirthday = (dateStr: string) => {
            if (!dateStr) return '1990-01-01';
            // 如果已经是 yyyy-MM-dd 格式，直接返回
            if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
              return dateStr;
            }
            // 否则转换为 yyyy-MM-dd 格式
            const date = new Date(dateStr);
            return date.toISOString().split('T')[0];
          };

          const testResponse = await fetch(`http://localhost:5000/api/user/phone/${userInfo.phone}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              name: userData.name ? userData.name.trim() : '',
              weight: userData.weight ? userData.weight.replace('kg', '').replace('未设置', '').trim() : '',
              height: userData.height ? userData.height.replace('cm', '').replace('未设置', '').trim() : '',
              birthday: formatBirthday(userData.birthday),
              img: userData.img && userData.img !== '/image/nv1.jpg' ? userData.img : null
            })
          });
          
          console.log('手机号API响应状态:', testResponse.status);
          
          if (testResponse.ok) {
            const result = await testResponse.json();
            console.log('手机号API保存成功:', result);
            setSuccessMessage('个人资料修改成功！');
            // 保存成功后重新获取数据并重新渲染
            await fetchUserProfile();
            // 3秒后清除成功消息
            setTimeout(() => setSuccessMessage(''), 3000);
            return;
          } else {
            const errorData = await testResponse.json();
            console.error('手机号API保存失败:', errorData);
            alert(`保存失败：${errorData.message || '未知错误'}`);
          }
        } catch (testError) {
          console.error('手机号API保存异常:', testError);
          alert('保存失败，请检查网络连接');
        }
      }
      
      // 如果所有API都失败，显示错误信息
      alert('保存失败，请检查网络连接或联系管理员');
    } catch (error) {
      console.error('保存用户资料失败:', error);
      alert('保存失败，请检查网络连接后重试');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="profile-page">
        <div className="header">
          <div className="back-btn" onClick={() => navigate('/index/profile')}>
            <LeftOutline />
          </div>
          <div className="page-title">个人资料</div>
          <div className="save-btn"></div>
        </div>
        <div className="loading-container">
          <div className="loading-text">加载中...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="profile-page">
      {/* 成功提示 */}
      {successMessage && (
        <div className="success-message">
          <span className="success-icon">✓</span>
          {successMessage}
        </div>
      )}
      
      {/* 头部导航 */}
      <div className="header">
        <div className="back-btn" onClick={() => navigate('/index/profile')}>
          <LeftOutline />
        </div>
        <div className="page-title">个人资料</div>
        <div className={`save-btn ${saving ? 'saving' : ''}`} onClick={handleSave}>
          {saving ? '保存中...' : '保存'}
        </div>
      </div>

      {/* 头像区域 */}
      <div className="avatar-container">
        <div className="avatar" onClick={() => document.getElementById('avatar-input')?.click()}>
          <img src={userData.img || userData.avatar} alt="用户头像" style={{ width: '100%', height: '100%', borderRadius: '50%', objectFit: 'cover' }} />
          <div className="avatar-overlay">
            <span className="avatar-text">点击更换头像</span>
        </div>
        </div>
        <input 
          id="avatar-input"
          type="file" 
          accept="image/*" 
          style={{ display: 'none' }}
          onChange={handleAvatarChange}
        />
      </div>

      {/* 信息卡片 */}
      <div className="info-card">
        <div className="info-item">
          <div className="info-label">名字</div>
          <div className="info-value">
            <input 
              type="text" 
              value={userData.name} 
              onChange={(e) => {
                setUserData({...userData, name: e.target.value});
                validateInput('name', e.target.value);
              }}
              className={`info-input ${errors.name ? 'error' : ''}`}
              placeholder="请输入姓名"
            />
            <RightOutline className="arrow-icon" />
          </div>
          {errors.name && <div className="error-message">{errors.name}</div>}
        </div>
        <div className="info-item">
          <div className="info-label">体重</div>
          <div className="info-value">
            <input 
              type="text" 
              value={userData.weight} 
              onChange={(e) => {
                setUserData({...userData, weight: e.target.value});
                validateInput('weight', e.target.value);
              }}
              className={`info-input ${errors.weight ? 'error' : ''}`}
              placeholder="请输入体重(kg)"
            />
            <RightOutline className="arrow-icon" />
          </div>
          {errors.weight && <div className="error-message">{errors.weight}</div>}
        </div>
        <div className="info-item">
          <div className="info-label">身高</div>
          <div className="info-value">
            <input 
              type="text" 
              value={userData.height} 
              onChange={(e) => {
                setUserData({...userData, height: e.target.value});
                validateInput('height', e.target.value);
              }}
              className={`info-input ${errors.height ? 'error' : ''}`}
              placeholder="请输入身高(cm)"
            />
            <RightOutline className="arrow-icon" />
          </div>
          {errors.height && <div className="error-message">{errors.height}</div>}
        </div>
        <div className="info-item">
          <div className="info-label">生日</div>
          <div className="info-value">
            <input 
              type="date" 
              value={userData.birthday} 
              onChange={(e) => {
                setUserData({...userData, birthday: e.target.value});
                validateInput('birthday', e.target.value);
              }}
              className={`info-input ${errors.birthday ? 'error' : ''}`}
            />
            <RightOutline className="arrow-icon" />
          </div>
          {errors.birthday && <div className="error-message">{errors.birthday}</div>}
        </div>
        <div className="info-item">
          <div className="info-label">手机号</div>
          <div className="info-value">
            <input 
              type="tel" 
              value={userData.phone} 
              onChange={(e) => {
                setUserData({...userData, phone: e.target.value});
                validateInput('phone', e.target.value);
              }}
              className={`info-input ${errors.phone ? 'error' : ''}`}
              placeholder="请输入手机号"
            />
            <RightOutline className="arrow-icon" />
          </div>
          {errors.phone && <div className="error-message">{errors.phone}</div>}
        </div>
      </div>
    </div>
  );
};

export default Individual;